<script setup lang="tsx">
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { PersonalTagVO } from '#/api/company/tag/personal/model';

import { onMounted, ref, watch } from 'vue';

import { useAccess } from '@vben/access';
import { useVbenModal } from '@vben/common-ui';

import { Popconfirm, Space } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  personalTagChangeSort,
  personalTagChangeStatus,
  personalTagGroupInfo,
  personalTagInfo,
  personalTagRemove,
} from '#/api/company/tag/personal';
import { ColorTag } from '#/components/dict';
import { DetailsModal } from '#/components/modal';
import { TableSwitch } from '#/components/table';

import { tagColumns, tagDetailsSchema } from '../data';
import tagModal from '../tag-modal.vue';

const props = defineProps<{
  tagGroupId: number | string;
  type: number | string;
}>();

const emit = defineEmits<{ reload: [] }>();

const { hasAccessByCodes } = useAccess();
const tableTitle = ref<string>('');

// 标签分级别权限
function getButtonAccess(key: string) {
  const accessMap: Record<number, Record<string, string>> = {
    1: {
      labelAdd: 'employee:label:add',
      labelEdit: 'employee:label:edit',
      labelRemove: 'employee:label:remove',
    },
    2: {
      labelAdd: 'employee:labelEmployee:add',
      labelEdit: 'employee:labelEmployee:edit',
      labelRemove: 'employee:labelEmployee:remove',
    },
  };

  const typeMap = accessMap[props.type];
  if (!typeMap) return false;

  const code = typeMap[key];
  return code ? hasAccessByCodes([code]) : false;
}

const [TagModal, tagModalApi] = useVbenModal({
  connectedComponent: tagModal,
});

const [TagDetailsModal, tagDetailsModalApi] = useVbenModal({
  connectedComponent: DetailsModal,
});

const gridOptions: VxeGridProps = {
  columns: tagColumns,
  height: 'auto',
  keepSource: false,
  pagerConfig: {
    enabled: false,
  },
  proxyConfig: {
    ajax: {
      query: async () => {
        const resp = await personalTagGroupInfo(props.tagGroupId);
        tableTitle.value = `${resp.name}`;
        return { rows: resp.labels || [] };
      },
    },
  },
  toolbarConfig: {
    enabled: true,
    custom: false,
    zoom: false,
  },
  rowConfig: {
    keyField: 'id',
    drag: true,
    isCurrent: true,
  },
  id: 'personal-tag-list',
  showOverflow: true,
};

const [BasicTable, tableApi] = useVbenVxeGrid({
  gridOptions,
  gridEvents: {
    rowDragend: async ({ newRow, oldRow, dragPos }) => {
      console.log(
        `拖拽完成，被拖拽行：${oldRow.name} 目标行：${newRow.name} 目标位置：${dragPos}`,
      );
      const tableList = tableApi.grid.getTableData()?.tableData ?? [];
      const sortedList = tableList.map((item, index) => {
        return { id: item.id, name: item.name, sort: index + 1 };
      });
      console.log('拖拽后表格数据：', sortedList);
      await personalTagChangeSort(sortedList as PersonalTagVO[]);
      emit('reload');
    },
  },
});

watch(
  () => props.tagGroupId,
  async () => {
    await tableApi.reload();
  },
);

onMounted(async () => {
  //
});

async function handleAdd() {
  tagModalApi.setData({ tagGroupId: props.tagGroupId, type: props.type });
  tagModalApi.open();
}

async function handlePreview(row: PersonalTagVO) {
  tagDetailsModalApi.setData(row);
  tagDetailsModalApi.open();
}

async function handleEdit(row: PersonalTagVO) {
  tagModalApi.setData({
    tagGroupId: props.tagGroupId,
    id: row.id,
    type: props.type,
  });
  tagModalApi.open();
}

async function handleDelete(row: PersonalTagVO) {
  await personalTagRemove([row.id]);
  await tableApi.query();
  emit('reload');
}

async function tagStatusUpdate(row: PersonalTagVO) {
  const data = {
    id: row.id,
    status: row.status,
  };
  await personalTagChangeStatus(data);
  emit('reload');
}

async function handleTagUpdated() {
  await tableApi.query();
  emit('reload');
}

// async function handleValidate() {
//   const result = await tableApi.grid.validate(true);
//   if (result) {
//     message.error('校验失败');
//   } else {
//     message.success('校验成功');
//   }
// }
</script>

<template>
  <BasicTable :table-title="tableTitle">
    <template #toolbar-tools>
      <Space>
        <a-button
          v-if="getButtonAccess('labelAdd')"
          type="primary"
          @click="handleAdd"
        >
          新增标签
        </a-button>
      </Space>
    </template>
    <template #name="{ row }">
      <ColorTag
        :color="row.listClass"
        :label="row.name"
        :disabled="row.status === '1'"
      />
    </template>
    <template #status="{ row }">
      <TableSwitch
        v-model:value="row.status"
        :api="() => tagStatusUpdate(row)"
        :disabled="!getButtonAccess('labelEdit')"
        @reload="tableApi.query()"
      />
    </template>
    <template #action="{ row }">
      <Space>
        <ghost-button
          v-access:code="['employee:label:query']"
          @click="handlePreview(row)"
        >
          详情
        </ghost-button>
        <ghost-button
          v-if="getButtonAccess('labelEdit')"
          @click="handleEdit(row)"
        >
          编辑
        </ghost-button>
        <Popconfirm
          placement="left"
          ok-type="danger"
          title="确认删除这条标签？"
          @confirm="handleDelete(row)"
        >
          <ghost-button
            danger
            v-if="getButtonAccess('labelRemove')"
            @click.stop=""
          >
            删除
          </ghost-button>
        </Popconfirm>
      </Space>
    </template>
  </BasicTable>
  <TagModal @reload="handleTagUpdated" />
  <TagDetailsModal :columns="tagDetailsSchema()" :api="personalTagInfo" />
</template>
